#! /usr/bin/perl
# This program traces y-Positions, source location and page for
# a DVI file that was generated using the -src-specials option.

use strict;

sub usage {
  my $msg = shift;
  die "$msg"."usage: perl redact.pl dir1 dir2 file.dvi\n";
}

scalar(@ARGV) == 3 or usage "";
my ($dir1, $dir2, $dvi) = @ARGV;

$|=1; print STDERR "reading DVI file...";
open REVERSE, "dvitype $dir2/$dvi |" or
  usage "Could not open $dir2/$dvi for analytics.\n\n";
my $vv;
my $p;
my %files;
while (<REVERSE>) {
  /beginning of page (\d+)/ and $p = $1;
  /vv:=(\d+)/ and $vv = $1;
  /src:(\d+) ([^']+)/ or next;
  $files{$2} = [] if not defined $files{$2};
  push @{$files{$2}}, [$1, $p, $vv];
}
close REVERSE;
$|=1; print STDERR "done\n";

my @pages;

sub add2page {
  my ($p, $y) = @_;
  $pages[$p] = {} if not defined $pages[$p];
  $pages[$p]->{$y} = 1;
  return;
}

for (sort keys %files) {
  my $f = $_;
  $|=1; print STDERR "diff for $_ ...";
  if (!(open DIFF, "diff -w $dir1/$_ $dir2/$_|")) {
    warn "Can not diff $dir1/$_ $dir2/$_!\n";
    next;
  }
  while (<DIFF>) {
    /^\d+(,\d+)?[ac](\d+(,\d+)?)/ or next;
    my ($from, $to) = split ",", $2;
    $to = $from if not defined $to;
    my $nearest;
    my $dist = 1000;
    for (@{$files{$f}}) {
      if ($from <= $_->[0] && $to >= $_->[0]) {
        add2page $_->[1], $_->[2];
      } else {
        if (abs($from - $_->[0]) < $dist) {
          $dist = abs($from - $_->[0]);
          $nearest = $_;
        }
        if (abs($to - $_->[0]) < $dist) {
          $dist = abs($from - $_->[0]);
          $nearest = $_;
        }
      }
    }
    add2page $nearest->[1], $nearest->[2]
      if $dist;
  }
  close DIFF;
  $|=1; print STDERR "done\n";
}

my $k;
for ($k = 0; $k < scalar(@pages); $k++) {
  next if !defined $pages[$k];
  print "$k: ", join(" ", sort { $a <=> $b } keys %{$pages[$k]}), "\n";
}
